package com.nbb.common.util;

import com.alibaba.fastjson.JSON;
import com.nbb.common.bean.BuriedPointVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kevin_zhang on 19/07/2017.
 */
public class ApiLogUtil {
    private static Logger logger = LoggerFactory.getLogger(ApiLogUtil.class);

    /**
     * 获取请求ip地址
     */
    public static String getIpAdress(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }

    /**
     * API接口日志收集
     *
     * @param request
     * @param resultObj
     * @param beginTime
     * @param endTime
     */
    public static void logCollection(HttpServletRequest request, Object resultObj, long beginTime,
                                     long endTime) {
        String requestId = MDC.get("logId");
        try {
            Map logMap = new HashMap();
            String url = request.getRequestURL().toString();
            String[] urlArr = url.split("/");
            String apiName = "";
            if (null != urlArr && urlArr.length > 0)
                apiName = urlArr[urlArr.length - 1];
            logMap.put("q_req_id", requestId);
            logMap.put("q_action", "stat_" + apiName);
            logMap.put("q_action_detail", url);
            logMap.put("q_opt_time", beginTime);
            logMap.put("q_opt_duration", (endTime - beginTime));

            Map maps = request.getParameterMap();
            if (!maps.isEmpty()) {
                logMap.put("q_req_param", maps);
            } else {
                /**
                 *  getParameter()的值是根据tomcat中设置的URIEncoding编码进行decode后得到的值等操作
                 *  getQueryString()则是，直接queryMB()原样输出
                 *  参考：https://my.oschina.net/gschen/blog/120553
                 */
                String queryStr = request.getQueryString();
                if (StringUtils.isNotBlank(queryStr)) {
                    queryStr = URLDecoder.decode(request.getQueryString(), "UTF-8");
                    logMap.put("q_req_param", queryStr);
                }
            }
            logMap.put("q_opt_result", resultObj);

            /**
             * 支付通知的几个接口，无返回值打印处理
             *//*
            if (apiName.contains("wechatNotify") ||
                    apiName.contains("alipayAppNotify") ||
                    apiName.contains("alipaySacnCodeNotify") ||
                    apiName.contains("alipayWapNotify")) {
                logMap.put("q_opt_result", "");
            } else {
                Object resObj = JSON.toJSONString(new ResultBean(ResultCode.RturnNullException));
                if (resultObj != null) {
                    if (resultObj instanceof String) {
                        resObj = resultObj;
                    } else {
                        resObj = JSON.toJSONString(resultObj);
                    }
                }
                logMap.put("q_opt_result", resObj);
            }*/

            String headerStr = request.getHeader("buriedPoint");
            if (StringUtils.isNotBlank(headerStr)) {
                try {
                    BuriedPointVo headers = JSON.parseObject(headerStr, BuriedPointVo.class);
                    logMap.put("q_uid", headers.getUid());
                    logMap.put("q_app_ver", headers.getAppVer());
                    logMap.put("q_app_code", headers.getAppCode());
                    logMap.put("q_channel", headers.getChannelNo());
                    logMap.put("q_dev_type", headers.getDeviceType());
                    logMap.put("q_dev_model", headers.getDeviceModel());
                    logMap.put("q_dev_imei", headers.getDevImei());
                    logMap.put("q_dev_Token", headers.getDeviceToken());
                    logMap.put("q_sys_version", headers.getSysVersion());
                    logMap.put("q_net", headers.getNetType());
                    logMap.put("q_ip", (StringUtils.isBlank(headers.getcIp()) ? getIpAdress(request) : headers.getcIp()));
                    logMap.put("q_loc", headers.getLoc());
                } catch (Exception ex) {
                    ex.printStackTrace();
                    logger.error("分析日志收集失败-请求头解析出错：" + headerStr);
                }
            }
            logger.info(JSON.toJSONString(logMap));
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("分析日志收集失败" + ex.getMessage());
        }
    }
}